package net.joyphper.ctrl.oper;

import net.joyphper.bean.User;
import net.joyphper.commons.Encrypt;
import net.joyphper.commons.ResponseJson;
import net.joyphper.commons.exception.AppTranException;
import net.joyphper.commons.security.Auth;
import net.joyphper.commons.security.SecurityUtil;
import net.joyphper.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller("net.joyphper.ctrl.oper.IndexCtrl")
public class IndexCtrl {
	@Autowired
	private SecurityUtil securityUtil;
	
	@Autowired
	private UserService userService;
	
	@RequestMapping("/oper/index.do")
	public String index(){
		return "/oper/index";
	}
	
	@RequestMapping("/oper/welcome.do")
	public String welcome(){
		return "/oper/welcome";
	}
	
	@RequestMapping(value="/oper/pwd.do",method=RequestMethod.GET)
	public String pwd(){
		return "/oper/pwd";
	}
	
	@RequestMapping(value="/oper/pwd.do",method=RequestMethod.POST)
	@ResponseBody
	public ResponseJson pwd(String ologinPwd,String loginPwd,String rloginPwd,String captcha){
		if(!this.securityUtil.compareCaptcha(captcha)){
			return ResponseJson.body(false, "验证码错误，请输入正确的验证码");
		}
		if(!loginPwd.equals(rloginPwd)){
			return ResponseJson.body(false, "密码和确认密码不一致，请重新输入");
		}
		
		Auth auth = this.securityUtil.getAuth();
		User user = this.userService.getUserById(auth.getId());
		
		String pwd = this.securityUtil.genPwd(user.getLoginMail(), ologinPwd);
		
		if(!user.getLoginPasswd().equals(pwd)){
			return ResponseJson.body(false, "原始密码错误，请重新输入");
		}
		
		pwd = Encrypt.md5(user.getLoginMail().trim()+loginPwd.toUpperCase());
		try {
			this.userService.updatePwd(pwd, auth.getId());
			return ResponseJson.body(true, "密码修改成功，下次请使用新密码登录");
		} catch (AppTranException e) {
			return ResponseJson.body(false, "密码修改失败，请稍后再试");
		}
		
	}
}
